package com.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 实现自己的路由过滤器
 */
@Component
public class IZuulFilter extends ZuulFilter {
    private static Logger LOGGER = LoggerFactory.getLogger(IZuulFilter.class);

    /**
     * 过滤的类型：pre 路由之前、routing 路由时、post 路由之后、error 发送错误调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤的顺序
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 在这里可以实现是否需要过滤的判断逻辑
     * 这里直接放开，true 需要过滤，默认为 false
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 具体的过滤逻辑，可以很复杂，写一写sql、nosql等的查询，判断底层的访问权限
     */
    @Override
    public Object run() throws ZuulException {
        // 获取Zuul提供的web 上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取http request 对象
        HttpServletRequest request = ctx.getRequest();
        LOGGER.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            LOGGER.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        LOGGER.info("Filter Ok！accessToken : {}",accessToken);
        return null;
    }


}
